package com.service.purchase;

import com.alibaba.excel.EasyExcel;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;
import com.dao.purchase.*;
import com.model.purchase.*;
import com.model.sys.SysUser;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static org.hamcrest.CoreMatchers.nullValue;

/**
 * 采购方案
 * 
 * @author chenjun
 *
 */
@Service
public class ProgramService {

	static final Logger logger = LoggerFactory.getLogger(ProgramService.class);

	@Autowired
	PurchaseMapper purchaseMapper;
	@Autowired
	ProgramMapper programMapper;
	@Autowired
	SupplyProgramMapper supplyProgramMapper;
	@Autowired
	ProgramMmMapper programMmMapper;
	@Autowired
	CommonService commonService;
	@Autowired
	InquiryMapper inquiryMapper;
	@Autowired
	PlanMmMapper planMapper;

	/**
	 * 采购方案列表
	 * 
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectProgramList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<PurchaseProgram> list = programMapper.selectProgramList(queryMap);

		int count = programMapper.selectProgramCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectProgramList:{}", list);

		return httpResult;
	}

	/**
	 * 方案详情
	 * 
	 * @param inqId
	 * @return
	 */
	public HttpResult selectProInfo(String gramId) {
		HttpResult httpResult = new HttpResult();
		PurchaseProgramVO purchaseProgramVO = programMapper.selectVO(gramId);
		if (purchaseProgramVO != null) {
			HashMap<String, Object> hashMap = new HashMap<String, Object>();
			hashMap.put("gramId", gramId);
			// 方案对应供应商
			List<PurchaseSupplyProgram> purchaseSupplyPrograms = supplyProgramMapper.selectProgramSupplyList(hashMap);
			purchaseProgramVO.setPurchaseSupplies(purchaseSupplyPrograms);
			// 方案对应物资明细
			List<PurchaseProgramMm> purchaseProgramMms = programMmMapper.selectProgramMmList(hashMap);
			purchaseProgramVO.setPurchaseProgramMms(purchaseProgramMms);
		}
		logger.info("selectProgramInfo:{}", purchaseProgramVO);
		httpResult.setData(purchaseProgramVO);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 * 
	 * @param purchasePlanMm
	 * @return
	 */
	@Transactional
	public HttpResult saveProgram(PurchaseProgramVO purchaseProgramVO) {
		if (purchaseProgramVO == null || purchaseProgramVO.getPurchaseProgramMms() == null
				|| purchaseProgramVO.getPurchaseSupplies() == null) {
			return HttpResult.error("方案参数不能为空!");
		}
		if (purchaseProgramVO.getPurchaseProgramMms().size() == 0) {
			return HttpResult.error("物资明细不能为空!");
		}
		if (purchaseProgramVO.getPurchaseSupplies().size() == 0) {
			return HttpResult.error("供应商不能为空!");
		}

		int result = 0;
		// 主表
		String gramIdString = purchaseProgramVO.getGramId();
		if (!StringUtils.isNotNull(gramIdString)) {
			String idString = UUID.randomUUID().toString();
			purchaseProgramVO.setGramId(idString);
			purchaseProgramVO.setGramCode(commonService.createCode("purchase_program", "gram_code"));
			result = programMapper.insert(purchaseProgramVO);
		} else {
			result = programMapper.update(purchaseProgramVO);
		}
		// 明细表
		List<PurchaseProgramMm> purchaseGraMms = purchaseProgramVO.getPurchaseProgramMms();
		if (purchaseGraMms != null) {
			// 先删除
			programMmMapper.deleteByGramId(purchaseProgramVO.getGramId());
			for (PurchaseProgramMm purchaseProgramMm : purchaseGraMms) {
				// 采购计划数量超出时，状态改为2
				BigDecimal sumDecimal = purchaseMapper.getPlanSum(purchaseProgramMm.getPlanId());
				BigDecimal stockDecimal = new BigDecimal(0);
				if (purchaseProgramMm.getGramPurNum() != null && purchaseProgramMm.getPlanPurNum() != null) {
					stockDecimal = purchaseProgramMm.getPlanPurNum().subtract(purchaseProgramMm.getGramPurNum());
					if (sumDecimal != null) {
						stockDecimal = stockDecimal.subtract(sumDecimal);
					}
				}
				PurchasePlanMm planMm = planMapper.load(purchaseProgramMm.getPlanId());
				if (stockDecimal.compareTo(BigDecimal.ZERO) <= 0) {
					planMm.setStatus(Global.NUMERICAL_TWO + "");
				} else {
					planMm.setStatus(Global.YES + "");
				}
				planMm.setPlanStockNum(stockDecimal);
				planMapper.update(planMm);

				purchaseProgramMm.setGramId(purchaseProgramVO.getGramId());
				purchaseProgramMm.setGramStockNum(stockDecimal);
				purchaseProgramMm.setGramCode(purchaseProgramVO.getGramCode());
				purchaseProgramMm.setGramName(purchaseProgramVO.getGramName());
				purchaseProgramMm.setStatus(purchaseProgramVO.getStatus());
				programMmMapper.insert(purchaseProgramMm);
			}
		}
		// 供应商
		List<PurchaseSupplyProgram> purchaseSupplyPrograms = purchaseProgramVO.getPurchaseSupplies();
		if (purchaseSupplyPrograms != null) {
			supplyProgramMapper.deleteByGramId(purchaseProgramVO.getGramId());
			for (PurchaseSupplyProgram purchaseSupplyProgram : purchaseSupplyPrograms) {
				purchaseSupplyProgram.setGramId(purchaseProgramVO.getGramId());
				supplyProgramMapper.insert(purchaseSupplyProgram);
			}
		}
		HttpResult httpResult = new HttpResult();
		if (result > 0) {
			httpResult.setData(purchaseProgramVO);
			httpResult.setMsg(purchaseProgramVO.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			return httpResult;
		} else {
			return HttpResult.error(purchaseProgramVO.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
	}

	/**
	 * 退回
	 * 
	 * @param purchasePlanMm
	 * @return
	 */
	@Transactional
	public HttpResult backProgram(PurchaseProgram purchaseProgram) {
		if (purchaseProgram == null) {
			return HttpResult.error("请求参数不能为空!");
		}
		int result = 0;
		HashMap<String, Object> hashMap = new HashMap();
		hashMap.put("gramId", purchaseProgram.getGramId());
		List<PurchaseInquiry> list = inquiryMapper.selectInquiryList(hashMap);
		if (list != null && list.size() > 0) {
			return HttpResult.error("该采购方案已生成询价书，不可回退！");
		}
		purchaseProgram.setStatus(Global.NO + "");
		result = programMapper.update(purchaseProgram);
		List<PurchaseProgramMm> programMms = programMmMapper.selectList(hashMap);
		for (PurchaseProgramMm programMm : programMms) {
			programMm.setStatus(Global.NO + "");
			programMmMapper.update(programMm);
		}

		if (result > 0) {
			return HttpResult.ok("回退成功");
		} else {
			return HttpResult.error("不存在此采购方案");
		}
	}

	@Transactional
	public HttpResult delProgramMm(String gramId, String planId) {
		if (!StringUtils.isNotNull(gramId) || !StringUtils.isNotNull(planId)) {
			return HttpResult.error("参数不能为空!");
		}
		PurchaseProgram model = programMapper.load(gramId);
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}
		HttpResult httpResult = new HttpResult();
		// 先把之前的计划剩余量改变
		PurchaseProgramMm programMm = programMmMapper.load(planId, gramId);
		PurchasePlanMm plan = planMapper.load(planId);
		if (plan.getPlanStockNum() != null && programMm.getGramStockNum() != null) {
			BigDecimal stockDecimal = plan.getPlanStockNum().add(programMm.getGramStockNum());
			plan.setPlanStockNum(stockDecimal);
		}
		plan.setStatus(Global.YES + "");
		planMapper.update(plan);
		// 删除数据
		int result = programMmMapper.delete(gramId, planId);

		if (result > 0) {
			httpResult.setMsg("删除成功！");
			httpResult.setCode(HttpStatus.SUCCESS_CODE);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 删除询价书
	 *
	 * @param inqId
	 * @return
	 */
	@Transactional
	public HttpResult delProgram(String gramId) {
		if (!StringUtils.isNotNull(gramId)) {
			return HttpResult.error("参数不能为空");
		}
		PurchaseProgram model = programMapper.load(gramId);
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}
		HttpResult httpResult = new HttpResult();
		// 剩余量改变
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("gramId", gramId);
		List<PurchaseProgramMm> programMms = programMmMapper.selectProgramMmList(hashMap);
		for (PurchaseProgramMm programMm : programMms) {
			PurchasePlanMm plan = planMapper.load(programMm.getPlanId());
			if (plan.getPlanStockNum() != null && programMm.getGramPurNum() != null) {
				plan.setPlanStockNum(plan.getPlanStockNum().add(programMm.getGramPurNum()));
			}
			plan.setStatus(Global.YES + "");
			planMapper.update(plan);
		}
		// 删除数据
		int result = programMapper.delete(gramId);
		programMmMapper.deleteByGramId(gramId);
		supplyProgramMapper.deleteByGramId(gramId);

		if (result > 0) {
			httpResult.setMsg("删除成功！");
			httpResult.setCode(HttpStatus.SUCCESS_CODE);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此采购方案！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void exportProgram(Map<String, Object> queryMap, HttpServletResponse response) {
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<PurchaseProgram> list = programMapper.selectProgramList(queryMap);

		logger.info("exportProgram:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), PurchaseProgram.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}

	public void exportProgramMm(Map<String, Object> queryMap, HttpServletResponse response) {
		List<PurchaseProgramMm> list = programMmMapper.selectProgramMmList(queryMap);

		logger.info("exportProgram:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), PurchaseProgramMm.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
